'use strict'

define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require('@yunke/art-dialog').default;
    require("../../../plugins/select2/select2");
    var util = require('@yunke/core/util').default;
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    var _ = require('lodash');
    require('../contract-common');
    var myMath = require('../../common/my-math');

    var ContractReceivableInvoice = angular.module('ContractReceivableInvoice', ['ContractCommonService']);

    ContractReceivableInvoice.filter('signOrIncomeAmount', function () {
            return function (contract) {
                //云客签约-直属区域/云客签约-联营区域/云客直销
                //使用签约金额
                var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
                if (contract.contract_property_id == limitContractArr[0] || contract.contract_property_id == limitContractArr[1] || contract.contract_property_id == limitContractArr[2]) {
                    return contract.sign_amount;
                } else {
                    return contract.income_amount ? contract.income_amount : 0;
                }
            }
        })
        .filter('sumInvoiceAmount', function () {
            return function (invoices) {
                var amount = 0;
                if (invoices) {
                    $.each(invoices, function (i, d) {
                        if (d.__type == 'delete') {
                            return;
                        }
                        amount = myMath.add(amount, d.invoice_amount);
                    });
                }

                return amount;
            }

        })
        .filter('remainInvoiceAmount', function () {
            return function (invoices, contract) {
                var amount = 0;
                if (invoices) {
                    $.each(invoices, function (i, d) {
                        if (d['__type'] == 'delete') {
                            return;
                        }
                        amount = myMath.add(amount, parseFloat(d.invoice_amount));
                    });
                }

                var limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
                if (contract.contract_property_id == limitContractArr[0] || contract.contract_property_id == limitContractArr[1] || contract.contract_property_id == limitContractArr[2]) {
                    return myMath.sub(contract.sign_amount, amount);
                } else {
                    return myMath.sub(contract.income_amount, amount);
                }

                return 0;
            }
        })
        .service('receivableInvoiceService', ['$rootScope', '$filter', 'contractCommonService', function ($rootScope, $filter, contractCommonService) {
            $rootScope.invoiceInfo = {};
            $rootScope.editFunds = [];

            var service = {
                onCloseInvoice: function ($dialogScope, invoiceType) {
                    if ($dialogScope.saveAndAdd === true) {
                        if (invoiceType === 1) {
                            $('#addVoiceButton').trigger('click');
                        }
                        if (invoiceType === 2) {
                            $('#addMainVoiceButton').trigger('click');
                        }
                    }
                },
                addAndSaveBtn: function ($dialog, $dialogScope) {
                    $($dialog.node).find('[i-id=ok]').after('<button type="button" i-id="okAdd" class="ui-dialog-autofocus" onclick="">确定并新增</button>');
                    $($dialog.node).find('[i-id=okAdd]').on('click', function () {
                        $dialogScope.saveAndAdd = true;
                        $($dialog.node).find('[i-id=ok]').trigger('click');
                    });
                    $($dialog.node).find('[i-id=cancel]').on('click', function () {
                        $dialogScope.saveAndAdd = false;
                    });
                },
                onInvoiceEditShow: function ($data, $dialog, $dialogScope, invoiceType, oldInvoice, contract, invoiceData) {
                    /**
                     * 打开发票编辑界面时初始化
                     * invoiceType: 发票类型：1：发票，2：子发票，3：红冲发票，4：收据 {number}
                     * oldInvoice: 原发票
                     * contract : 合同基本信息 {object}
                     * invoiceData : 合同发票已录入数据 {array}
                     */

                    var now = new Date(),
                        now_y = now.getFullYear(),
                        now_m = now.getMonth() + 1,
                        now_M = (now_m > 9) ? now_m : ('0' + now_m),
                        now_d = now.getDate(),
                        now_D = (now_d > 9) ? now_d : ('0' + now_d),
                        format_now = now_y + '-' + now_M + '-' + now_D;

                    if (!oldInvoice) {
                        setTimeout(function () {
                            //默认设置发票类型为服务票
                            $('#category').data('select2').updateSelection({id: 1, text: '服务票'});
                            $dialogScope.invoiceInfo.invoice_category = 1;
                            $('#idInvoiceCompany').data('select2').updateSelection({
                                id: 'f775a92e-0071-11e5-bed8-00155d02c832',
                                text: '明源云客'
                            });
                            $dialogScope.invoiceInfo.invoice_company_id = 'f775a92e-0071-11e5-bed8-00155d02c832';
                            $dialogScope.invoiceInfo.invoice_date = format_now;
                        }, 0);

                    }

                    //如果合同类型为 “联营签约-云客结算” 设置默认值
                    $dialogScope.requiredProposer = 0;
                    if (contract.contract_property_id == "7f856e81-fce8-11e4-bed8-00155d02c832" && oldInvoice == null) {
                        setTimeout(function () {
                            //客户名称
                            $dialogScope.invoiceInfo.customer_name = contract.company_name;
                            //开票单位
                            $('#idInvoiceCompany').data('select2').updateSelection({
                                id: 'f775a92e-0071-11e5-bed8-00155d02c832',
                                text: '明源云客'
                            });
                            $dialogScope.invoiceInfo.invoice_company_id = 'f775a92e-0071-11e5-bed8-00155d02c832';
                            //开票时间
                            $dialogScope.invoiceInfo.invoice_date = format_now;
                            //开票金额
                            $dialogScope.invoiceInfo.invoice_amount = contract.income_amount;
                            //声请人是否必须
                            $dialogScope.requiredProposer = 0;
                        }, 0);
                    }

                    if (invoiceType == 1 || invoiceType == 4) {
                        $dialogScope.maxInvoiceAmount = $filter('remainInvoiceAmount')(invoiceData, contract);
                    }


                    if (invoiceType === 1) {
                        this.addAndSaveBtn($dialog, $dialogScope);
                    }

                    //新建发票
                    $dialogScope.invoiceInfo = {
                        invoiceSummarys: [],
                        contract_id: $data,
                        is_receipt: invoiceType == 4 ? 1 : 0,
                        is_red_invoice: invoiceType == 3 ? 1 : 0,
                        is_child_invoice: invoiceType == 2 ? 1 : 0,
                        is_main_invoice: 0
                    };

                    //开票金额变更时，重新计算分摊金额
                    $dialogScope.$watch('invoiceInfo.invoice_amount', function () {
                        $dialogScope.shareAmount();
                    });

                    //分摊发票金额
                    $dialogScope.shareAmount = function () {
                        var items = $dialogScope.editInvoiceReceivables || [];
                        var invoiceAmount = ($dialogScope.invoiceInfo.invoice_amount || 0) - ($dialogScope.invoiceInfo.receivables_amount || 0);
                        $.each(items, function (i, d) {
                            if (!d._checked || invoiceAmount <= 0) {
                                d.cur_billing_amount = 0;
                                return true;
                            }
                            d.cur_billing_amount = myMath.sub(d.receivable_amount, d.billing_amount);
                            invoiceAmount -= d.cur_billing_amount;
                            if (invoiceAmount < 0) {
                                d.cur_billing_amount += invoiceAmount;
                            }
                        });
                    };

                    $dialogScope.orgianlInvoice = oldInvoice;
                    $dialogScope.invoiceType = invoiceType;
                    $dialogScope.invoiceName = invoiceType == 4 ? '收据' : '发票';

                    //下拉框设置
                    //发票类别
                    $dialogScope.ddlConfigInvoiceCategory = {
                        allowClear: false,
                        data: [{id: 1, text: '服务票'}, {id: 0, text: '销售票'}],
                        minimumResultsForSearch: 'Infinity'

                    };


                    //发票类型
                    $dialogScope.ddlConfigInvoiceType = {
                        allowClear: false,
                        data: [{id: "0", text: '增值税普通发票'}, {id: "1", text: '增值税专用发票'}],
                        minimumResultsForSearch: 'Infinity'
                    };

                    //摘要类型
                    $dialogScope.ddlConfigInvoiceSummaryType = {
                        allowClear: false,
                        data: _.map(['软件技术服务费', '软件服务费', '服务费', '明源云客电子商务平台－移动销售系统V1.0', '明源云客来访登记系统V1.0', '广告费', '广告发布费'], x => ({
                            id: x,
                            text: x
                        })),
                        minimumResultsForSearch: 'Infinity'
                    };

                    //申请人
                    $dialogScope.ddlConfigInvoiceProposer = {
                        allowClear: false,
                        ajax: {
                            url: api_prefix + "erp-interface/get-users",
                            dataType: 'json',
                            delay: 250,
                            data: function (term) {
                                return {
                                    keyword: term,
                                    limit: 10
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode === "0") {
                                    data = json.data;
                                }
                                return {results: data};
                            },
                            cache: true
                        },
                        escapeMarkup: function (markup) {
                            return markup;
                        }, // let our custom formatter work
                        minimumInputLength: 1,
                        onchange2: function (newVal) {
                            $dialogScope.invoiceInfo.user_name = newVal.UserName;
                            $dialogScope.invoiceInfo.area_name = newVal.BUName;
                        }
                    };
                    //开票单位
                    $dialogScope.ddlConfigInvoiceCompany = {
                        allowClear: false,
                        data: [],
                        onchange2: function (newVal) {
                            $dialogScope.invoiceInfo.invoice_company_name = newVal.BUName;
                        }
                    };

                    contractCommonService.getInvoiceBusinessUnit(function (data) {
                        var ddlData = [];
                        $.each(data, function (i, d) {
                            //只显示明源云客
                            if (d.BUGUID == 'f775a92e-0071-11e5-bed8-00155d02c832') {
                                ddlData.push({id: d.BUGUID, text: d.BUName});
                            }

                        });
                        $dialogScope.ddlConfigInvoiceCompany.data = ddlData;
                        $dialogScope.$applyAsync();
                    });

                    //主发票ddl
                    $dialogScope.ddlConfigMainInvoice = {
                        ajax: {
                            url: api_prefix + "receivable/get-parent-invoice-info",
                            dataType: 'json',
                            delay: 250,
                            data: function (term, page) {
                                return {
                                    keyword: term, // search term
                                    page: page
                                };
                            },
                            results: function (json, page) {
                                var data = [];
                                if (json.retCode == 0) {
                                    data = json.data;
                                    $.each(data, function (i, d) {
                                        d.id = d.invoice_id;
                                        d.text = d.invoice_no;
                                    });
                                }
                                return {results: data};
                            },
                            cache: true
                        },
                        minimumInputLength: 1
                    };


                    if (oldInvoice) {
                        $dialogScope.invoiceInfo = angular.extend({}, oldInvoice);
                        setTimeout(function () {
                            $('.idProposer:last').data('select2').updateSelection({text: oldInvoice.UserName || ''});
                        }, 500);
                    }

                    //获取应收信息列表
                    if (invoiceType != 3) {
                        //非红冲发票去应收信息
                        contractCommonService.getContractReceivable($data, function (json) {
                            json.forEach(function (v) {
                                v.cur_billing_amount = 0;
                            });
                            $dialogScope.editInvoiceReceivables = json;
                            $dialogScope.$applyAsync();
                        });
                    } else {
                        $dialogScope.invoiceInfo.red_by_invoice_id = $dialogScope.invoiceInfo.invoice_id;
                        $dialogScope.invoiceInfo.invoice_id = null;//红冲发票新增记录
                        $dialogScope.invoiceInfo.is_red_invoice = 1;
                        $dialogScope.invoiceInfo.invoice_amount = -$dialogScope.invoiceInfo.invoice_amount;
                        setTimeout(function () {
                            $('.idInvoiceCompany:last').data('select2').updateSelection({text: oldInvoice.BUName || ''});
                            $('.idMainInvoice:visible').length && $('.idMainInvoice:visible').data('select2').updateSelection({text: oldInvoice.main_invoice_no});
                        }, 500);

                        $.each($dialogScope.invoiceInfo.invoiceSummarys, function (i, d) {
                            d.summary_amount = -Math.abs(d.summary_amount);
                        });
                    }

                    $dialogScope.totalEqualAmount = function () {
                        if ($dialogScope.invoiceInfo.invoice_amount) {
                            return $dialogScope.totalAmount() != $dialogScope.invoiceInfo.invoice_amount;
                        } else {
                            return false;
                        }
                    };

                    /**
                     * 计算摘要金额总和
                     * @returns {number}
                     */
                    $dialogScope.totalAmount = function () {
                        var sum = 0;

                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        if (items) {
                            for (var i = 0; i < items.length; i++) {
                                var item = items[i];
                                sum += parseFloat(item.summary_amount);
                            }
                        }

                        return sum;
                    };

                    //新建发票摘要
                    $dialogScope.newInvoiceAbstract = function () {
                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        var id;
                        id = items.length ? items[0].id + 1 : 1;
                        var summary = {
                            id: id,
                            summary_type: '软件技术服务费',
                            summary_amount: '0'
                        };
                        items.unshift(summary);
                    };

                    //删除发票摘要
                    $dialogScope.removeInvoiceAbstract = function (idx) {
                        var item;
                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        items.splice(idx, 1);
                    };

                    $dialogScope.vaildSummaryRequired = function () {
                        var items = $dialogScope.invoiceInfo.invoiceSummarys || [];
                        if (items.length === 0) {
                            return true;
                        }
                        var rst = $.grep(items, function (d, i) {
                            return d.summary_amount == null;
                        })
                        return rst.length > 0;
                    };
                    $dialogScope.vaildSummaryNumber = function () {
                        var items = $dialogScope.invoiceInfo.invoiceSummarys;
                        var rst = $.grep(items, function (d, i) {
                            return d.summary_amount && !d.summary_amount.toString().match(/^-?[\d]*(\.[\d]+)*$/);
                        })
                        return rst.length > 0;
                    };

                    var self = this;
                    $dialogScope.showInvoiceImport = function () {
                        $dialogScope.query = {
                            keyword: '',
                            execute: function () {
                                contractCommonService.getCanUseInvoiceInfo($dialogScope.invoiceInfo.contract_id, $dialogScope.query.keyword, function (data) {
                                    $dialogScope.importInvoices = data;
                                    $dialogScope.$applyAsync();
                                });
                            }
                        };
                        self.onInvoiceImportShow($dialogScope, '引入未关联合同发票', $dialogScope.importInvoice);
                    };
                    $dialogScope.importInvoice = function (item) {
                        $dialogScope.invoiceInfo = angular.extend($dialogScope.invoiceInfo, angular.copy(item), {contract_id: $dialogScope.invoiceInfo.contract_id});
                        $dialogScope.$applyAsync();

                        setTimeout(function () {
                            $('.idProposer:visible').length && $('.idProposer:visible').data('select2').updateSelection({text: $dialogScope.invoiceInfo.UserName});
                            $('.idInvoiceCompany:visible').length && $('.idInvoiceCompany:visible').data('select2').updateSelection({text: $dialogScope.invoiceInfo.BUName});
                            $('.idMainInvoice:visible').length && $('.idMainInvoice:visible').data('select2').updateSelection({text: $dialogScope.invoiceInfo.main_invoice_no});
                        }, 100);
                    }
                },
                onInvoiceImportShow: function ($dialogScope, title, callback) {
                    /**
                     * 引入未关联合同界面初始化
                     */

                    $dialogScope.importInvoices = [];

                    $dialogScope.query.execute();

                    $dialogScope.selectInvoice = function (item) {
                        $.each($dialogScope.importInvoices, function (i, d) {
                            d.__selected = false;
                        })
                        item.__selected = true;
                    };

                    var d = dialog({
                        title: title,
                        content: $('.importInvoiceDlg:last'),
                        fixed: true,
                        width: 650,
                        height: 450,
                        okValue: "确定",
                        ok: function () {
                            var selectedInvoices = $.grep($dialogScope.importInvoices, function (d, i) {
                                return d.__selected == true;
                            })
                            if (selectedInvoices.length) {
                                if (callback && typeof callback == 'function') {
                                    callback(selectedInvoices[0]);
                                    $dialogScope.$applyAsync();
                                }
                            } else {
                                util.alert('请选择发票记录');
                                return false;
                            }

                            return true;
                        },
                        cancel: function () {
                        }
                    });
                    d.showModal();

                },
                editInvoiceSave: function ($data, $dialog, $dialogScope, callback, contract, isAdd) {
                    /**
                     * 保存新增发票
                     * isAdd 1: 发票,收据新增,红冲发票
                     *       0 :  编辑 发票,收据
                     */

                    //客户名称不等于签约客户全称时提示发票名称与签约客户全称不一致.
                    //云客签约-直属区域 : 7f83719a-fce8-11e4-bed8-00155d02c832
                    //云客签约-联营区域 : 7f8422d0-fce8-11e4-bed8-00155d02c832
                    //云客直销 : efa353cd-51ca-11e8-a035-00155d02c83e
                    var yunkeArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];

                    //联营签约-云客区域: 7f856e81-fce8-11e4-bed8-00155d02c832
                    //客户名称不等于合同签署公司时提示发票名称与签约客户全称不一致，是否继续提交
                    var lianyingContract = '7f856e81-fce8-11e4-bed8-00155d02c832';


                    var customerIsValid = false,
                        customerNotValidTips = '';

                    if (contract.contract_property_id == yunkeArr[0] || contract.contract_property_id == yunkeArr[1] || contract.contract_property_id == yunkeArr[2]) {
                        if ($dialogScope.invoiceInfo.customer_name != contract.customer_full_name) {
                            customerIsValid = true;
                            customerNotValidTips = '发票名称与签约客户全称不一致，是否继续提交?';
                        }

                    }

                    if (contract.contract_property_id == lianyingContract) {
                        if ($dialogScope.invoiceInfo.customer_name != contract.company_name) {
                            customerIsValid = true;
                            customerNotValidTips = '发票名称与合同签署公司不一致，是否继续提交';
                        }
                    }

                    var invoiceInfo = $dialogScope.invoiceInfo;
                    var checkedReceivables = $.grep($dialogScope.editInvoiceReceivables || [], function (d, i) {
                        return d._checked == true;
                    })

                    //红冲此发票不需要弹出选项
                    if (!$dialogScope.data.isHongChongInvoice) {
                        if (checkedReceivables.length <= 0) {
                            util.alert('请至少勾选一条应收信息');
                            return false;
                        }
                    }

                    invoiceInfo.invoiceReceivables = checkedReceivables;

                    //校验
                    if ($('.error:visible').length) {
                        return false;
                    }

                    if (customerIsValid && isAdd == 1) {
                        util.confirm(customerNotValidTips, {
                            ok: function () {
                                service.cofirmSaveInvoice($dialog, invoiceInfo, callback, {
                                    isHongChongInvoice: $dialogScope.data.isHongChongInvoice
                                });
                            }
                        });
                    } else {
                        service.cofirmSaveInvoice($dialog, invoiceInfo, callback, {
                            isHongChongInvoice: $dialogScope.data.isHongChongInvoice
                        });
                    }

                    return false;

                },
                cofirmSaveInvoice: function ($dialog, invoiceInfo, callback, options) {
                    var post_data = invoiceInfo;
                    var url;
                    url = api_prefix + "/receivable/save-invoice-receivable";
                    //如果是红冲发票，用这个接口
                    if (options.isHongChongInvoice) {
                        url = api_prefix + '/invoice/save-invoice';
                    }
                    util.myAjax({
                        url: url,
                        type: "POST",
                        context: this,
                        data: post_data,
                        async: false,
                        success: function (json) {
                            if (json.retCode == 0) {
                                util.alert("保存成功");
                                if (callback) {
                                    callback();
                                }
                                $dialog.close();
                            } else {
                                util.alert("保存失败：" + json.errMsg);
                                return false;
                            }
                        }
                    });
                },
                deleteInvoice: function (invoiceInfo, callback) {
                    /**
                     * 删除发票
                     */
                    util.confirm('确定要删除此发票吗?', {
                        ok: function () {
                            var post_data = {invoice_id: invoiceInfo.invoice_id};
                            var url;
                            url = api_prefix + "/receivable/delete-invoice";

                            util.myAjax({
                                url: url,
                                type: "POST",
                                context: this,
                                data: post_data,
                                success: function (json) {
                                    if (json.retCode == 0) {
                                        invoiceInfo.__isdelete = 1;
                                        util.alert("删除成功");
                                        $rootScope.$applyAsync();
                                        if (callback) {
                                            callback();
                                        }
                                    } else {
                                        util.alert("删除失败：" + json.errMsg);
                                    }
                                }
                            });
                        }
                    });
                },
                convertToInvoice: function (invoiceInfo, $event) {
                    /**
                     * 收据转为发票
                     */
                    util.confirm('确定要把此收据转为发票吗?', {
                        ok: function () {
                            var post_data = angular.extend({}, invoiceInfo, {is_receipt: 0});
                            var url;
                            url = api_prefix + "/receivable/save-invoice-receivable";

                            util.myAjax({
                                url: url,
                                type: "POST",
                                context: this,
                                data: post_data,
                                success: function (json) {
                                    if (json.retCode == 0) {
                                        util.alert("收据转为发票成功", {
                                            ok: function () {
                                                $event && $($event.target).parent().find('[type=edit]').trigger('click');
                                                invoiceInfo.is_receipt = 0;
                                                $rootScope.$applyAsync();
                                            }
                                        });
                                    } else {
                                        util.alert("收据转为发票失败：" + json.errMsg);
                                    }
                                }
                            });
                        }
                    });
                }
            }
            return service;
        }]);

    module.exports = ContractReceivableInvoice;
});
